package main

import (
	"fmt"
	"github.com/sendgrid/sendgrid-go"
	"github.com/sendgrid/sendgrid-go/helpers/mail"
)

type EmailSender struct {
	FromName string
	FromEmail string
	Subject string
	Content string
	config *SendGridConfig
}

func NewEmailSender(conf *SendGridConfig) *EmailSender {
	return &EmailSender{
		config: conf,
		FromName: conf.FromName,
		FromEmail: conf.FromEmail,
	}
}

func (this *EmailSender) SetFromName(fromName string) *EmailSender {
	this.FromName = fromName
	return this
}

func (this *EmailSender) SetFromEmail(fromEmail string) *EmailSender  {
	this.FromEmail = fromEmail
	return this
}

func (this *EmailSender) SetSubject (subject string) *EmailSender  {
	this.Subject = subject
	return this
}

func (this *EmailSender) SetContent (content string) *EmailSender  {
	this.Content = content
	return this
}

func (this *EmailSender) Send(emailAddress string) error  {
	from := mail.NewEmail(this.FromName, this.FromEmail)
	to := mail.NewEmail(emailAddress, emailAddress)
	message := mail.NewSingleEmail(from, this.Subject, to, this.Content, this.Content)
	client := sendgrid.NewSendClient(this.config.ApiKey)
	response, err := client.Send(message)
	if err != nil {
		log.Error(err)
		return err
	}

	log.Info(response.Body)

	return nil
}

func (this *EmailSender) SendTaskCompletedEmail(address string, URL string) error {
	this.SetSubject(`IPA2S3 Task completed`)
	this.SetContent(fmt.Sprintf("Dear \n The download page is \n %s", URL))

	return this.Send(address)
}

func (this *EmailSender) SendTaskFailedEmail(address string, err error) error {
	this.SetSubject(`IPA2S3 Task Failed`)
	this.SetContent(fmt.Sprintf("Dear \n Error: \n %s", err.Error()))

	return this.Send(address)
}